#pragma once

#include "IWebsocketServer.h"
#include <sstream>
#include "WLog.h"
#include <map>
#include <set>

class WWebsocketServer;
struct WWebsocketCbMsg
{
    WWebsocketServer *wsServer = nullptr;
    bool sslFlag = false;
};

class WWebsocketServer: public IWebsocketServer
{
public:
    WWebsocketServer(mg_mgr *mgr = nullptr);
    virtual ~WWebsocketServer();
    virtual bool startWsServer(int port);
    virtual bool startWssServer(int port, string certPath, string keyPath);
    virtual void setListener(IWebsocketServerCb *listener);
    virtual bool run();
    virtual bool stop(); // mg_mgr是外部传入时，外部需要主动调用stop函数
    virtual bool sendMsg(mg_connection *wsConnection, const string &msg);
    virtual bool disconnect(mg_connection *wsConnection);

private:
    mg_mgr *_mgr = nullptr;
    mg_connection *_wsServerConn = nullptr;
    mg_connection *_wssServerConn = nullptr;
    bool _selfMgrFlag = false;
    volatile int _wsPort = -1;
    volatile int _wssPort = -1;
    string _certPath = "";
    string _keyPath = "";
    WWebsocketCbMsg _wsCbMsg;
    WWebsocketCbMsg _wssCbMsg;
    IWebsocketServerCb *_listener = nullptr;

    void recvWsRequestMsg(struct mg_connection *conn, int msgType, void *msgData, void *cbData);
    void logHttpRequestMsg(mg_connection* conn, mg_http_message* httpCbData);

    static void recvWsRequestMsgCb(struct mg_connection *conn, int msgType, void *msgData, void *cbData);
};

